<template>
  <Button type="primary" :loading="dLoading" class="ivu-btn-add" icon="md-cloud-download" @click="exportSubmit">导出
  </Button>
</template>

<script>


import {sessionStorage} from "@/common/cacheUtils";
import _deepclone from 'lodash/cloneDeep'

export default {
  name: "download-button",
  props: {
    post: {
      type: Boolean,
      default: false,
    },
    api: {
      type: String,
    },
    exportFormBefore: {
      type: Function,
      default: () => {
      }
    },
    queryForm: {
      type: Object,
      default: {},
    },

  },
  data() {
    return {
      dLoading: false,
      dataToQuery: {},
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
    }
  },
  methods: {
    downloadTable({formData, action = '', fileName = ''}) {
      let data = {}
      for (let key in formData) {
        let value = formData[key]
        if (value instanceof Array) {
          data[key + '[]'] = value.toString()
        }
        if (value) {
          data[key] = value
        }
      }
      this.dLoading = true;
      if (this.post) {
        this.$http.post(action, data, {responseType: 'blob'}).then(res => {
          // this.$Spin.hide();
          const aLink = document.createElement("a");
          aLink.target = '_blank'
          let blob = new Blob([res.data], {
            type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
          });
          aLink.href = URL.createObjectURL(blob)
          if (!fileName) {
            let dis = res.headers.map['content-disposition']
            fileName = dis.toString().split('attachment;filename=')[1]
            fileName = decodeURIComponent(decodeURI(fileName))
          }
          aLink.download = fileName //标题
          aLink.click()
          document.body.appendChild(aLink)
          this.dLoading = false;
        }).catch((r) => {
          console.error(r)
          // this.$Spin.hide();
          this.dLoading = false;
          this.$Message.error('下载文件出现错误，请联系管理员！')
        })
      } else {
        this.$http.get(action, {
          params: data,
          responseType: 'blob'
        }).then(res => {
          // this.$Spin.hide();
          const aLink = document.createElement("a");
          aLink.target = '_blank'
          let blob = new Blob([res.data], {
            type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
          });
          aLink.href = URL.createObjectURL(blob)
          if (!fileName) {
            let dis = res.headers.map['content-disposition']
            fileName = dis.toString().split('attachment;filename=')[1]
            fileName = decodeURIComponent(decodeURI(fileName))
          }
          aLink.download = fileName //标题
          aLink.click()
          document.body.appendChild(aLink)
          this.dLoading = false;
        }).catch((r) => {
          console.error(r)
          // this.$Spin.hide();
          this.dLoading = false;
          this.$Message.error('下载文件出现错误，请联系管理员！')
        })
      }

    },
    exportSubmit() {
      let token = sessionStorage('token').get('Authorization');
      this.dataToQuery.token = token
      this.dataToQuery.exportPerson = this.currentUser.userName;
      this.dataToQuery.exportDate = new Date();
      this.dataToQuery.exportPhone = this.currentUser.mobileNumber;
      this.exportFormBefore(this.dataToQuery);
      this.downloadTable({
        formData: this.dataToQuery,
        action: this.api,
        dLoading: this.dLoading
      });

    },
  },
  computed: {
    queryData() {
      return this.queryForm;
    }
  },
  watch: {
    queryData: {
      handler(v) {
        console.log('download-button', v)
        this.dataToQuery = _deepclone(v)
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>

<style scoped>

</style>
